#!/usr/bin/env python
# -*- coding:utf-8 -*-

import datetime
import math
import json

from sqlalchemy import or_

from app import db
from ..models.orderModel import SsoUser
from ..utils import commons
from ..utils.response_code import RET, error_map_EN
from ..utils.loggings import loggings



class SsoUserController(SsoUser):

    # add
    @classmethod
    def add(cls, **kwargs):
        from ..utils.generate_id import GenerateID
        orderID = GenerateID.create_random_id()

        try:
            model = SsoUser(
                orderID=kwargs.get('orderID'),
                userID=kwargs.get('userID'),
                thingID=kwargs.get('thingID'),
                isdelete=kwargs.get('isdelete'),
                addTime=kwargs.get('addTime'),

            )
            results = {
                'add_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'orderID': model.orderID,
                'userID': model.userID,
                'thingID': model.thingID,

            }
            filter_list = [cls.orderID == kwargs.get('orderID')]
            res = db.session.query(cls).filter(or_(*filter_list)).all()
            db.session.add(model)
            db.session.commit()
            if len(res) > 0:
                return {'code': RET.DATAEXIST, 'message': error_map_EN[RET.DATAEXIST],
                        'data': {'error': '提交的(orderID)值有重复'}}
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # get
    @classmethod
    def get(cls, **kwargs):
        try:
            filter_list = []
            if kwargs.get('orderID'):
                filter_list.append(cls.orderID == kwargs['orderID'])
            else:
                if kwargs.get('isdelete') is not None:
                    filter_list.append(cls.isdelete == kwargs.get('isdelete'))
                if kwargs.get('status') is not None:
                    filter_list.append(cls.status == kwargs.get('status'))
                if kwargs.get('addTime'):
                    filter_list.append(cls.addTime == kwargs.get('addTime'))


            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            sso_user_info = db.session.query(cls).filter(*filter_list)

            count = sso_user_info.count()
            pages = math.ceil(count / size)
            sso_user_info = sso_user_info.limit(size).offset((page - 1) * size).all()

            results = commons.query_to_dict(sso_user_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages, 'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # delete
    @classmethod
    def delete(cls, **kwargs):
        try:
            filter_list = []
            if kwargs.get('orderID'):
                primary_key_list = []
                for primary_key in str(kwargs.get('orderID')).replace(' ', '').split(','):
                    primary_key_list.append(cls.orderID == primary_key)
                filter_list.append(or_(*primary_key_list))

            else:
                if kwargs.get('isdelete') is not None:
                    filter_list.append(cls.isdelete == kwargs.get('isdelete'))
                if kwargs.get('addTime'):
                    filter_list.append(cls.addTime == kwargs.get('addTime'))

            res = db.session.query(cls).filter(*filter_list).with_for_update()

            results = {
                'delete_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'orderID': []
            }
            for query_model in res.all():
                results['orderID'].append(query_model.orderID)

            res.delete()
            db.session.commit()

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # update
    @classmethod
    def update(cls, **kwargs):
        try:

            filter_list = [cls.isdelete == 0]
            filter_list.append(cls.orderID == kwargs.get('orderID'))

            res = db.session.query(cls).filter(*filter_list).with_for_update()

            results = {
                'update_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'orderID': res.first().orderID,

            }

            res.update(kwargs)
            db.session.commit()

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()